import sys
try:
    from functools import wraps
except ImportError:
    from django.utils.functional import wraps  # Python 2.4 fallback.
from django.utils.decorators import available_attrs
from django.http import Http404

def autodiscover():
    """
    Automatically loads management definitions from manage modules in
    installed apps.
    """
    from django.conf import settings
    from django.utils.importlib import import_module
    from django.utils.module_loading import module_has_submodule
    
    for app in settings.INSTALLED_APPS:
        mod = import_module(app)
        # Attempt to import the app's options module.
        try:
            setattr(sys.modules[__name__],'_app_name',app)
            #sys.stderr.write("Importing %s.manage..." % app); sys.stderr.flush();
            ManagementInterfaces = None
            import_module('%s.manage' % app)
            #sys.stderr.write("Done!\n"); sys.stderr.flush();
        except:
            # Decide whether to bubble up this error. If the app just
            # doesn't have an options module, we can ignore the error
            # attempting to import it, otherwise we want it to bubble up.
            #sys.stderr.write(" module not found!\n"); sys.stderr.flush();
            if module_has_submodule(mod, 'manage'):
                raise
    
class ManagementInterfaces:
    def __init__(self):
        self.interfaces = {}
        self.indirect_interfaces = {}
        
    def register_interface(self, app_title, auth_level, command, view, indirect=False):
        for level in auth_level.split(';'):
            if indirect:
                if not app_title in self.indirect_interfaces: self.indirect_interfaces[app_title] = {}
                if not level in self.indirect_interfaces[app_title]: self.indirect_interfaces[app_title][level] = {}
                self.indirect_interfaces[app_title][level][command] = view
            else:
                if not app_title in self.interfaces: self.interfaces[app_title] = {}
                if not level in self.interfaces[app_title]: self.interfaces[app_title][level] = {}
                self.interfaces[app_title][level][command] = view
            
    def get_interfaces(self):
        return self.interfaces
    
    def get_indirect_interfaces(self):
        return self.indirect_interfaces
    
Management = ManagementInterfaces()